package com.nineclock.attendance.task;

import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    AttendGroupMapper attendGroupMapper;

    @Autowired
    SysUserFeign userFeign;

    @Autowired
    AttendPunchService attendPunchService;

    @XxlJob("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail() throws MessagingException, IOException{
        //1. 获取企业的id集合
        List<AttendGroup> attendGroups = attendGroupMapper.selectList(null);
        // 把考勤组中的企业id 抽取出来
        Set<Long> companyIdSet = attendGroups.stream().map(attendGroup -> {
            return attendGroup.getCompanyId();
        }).collect(Collectors.toSet());

        //需要给每一个企业管理员发送邮件
        for (Long companyId : companyIdSet) {

            //2. 生成excel
            String excelPath = attendPunchService.generateExcelReportByCompanyId(companyId);

            //3. 获取每个企业对应的管理员
            SysCompanyUserDTO companyAdminUser = userFeign.queryAdminByCompanyId(companyId).getData();

            //4. 发送邮件
            this.sendMail(companyAdminUser.getEmail(), companyAdminUser.getCompanyName(), excelPath);

        }
    }

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;


    public void sendMail(String to, String companyName, String excelPath) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(username);
        mimeMessageHelper.setSubject("考勤邮件");
        mimeMessageHelper.setText("考勤邮件，请查收");
        mimeMessageHelper.setTo(to);

        mimeMessageHelper.addAttachment("考勤邮件.xls", new File(excelPath));


        javaMailSender.send(mimeMessage);
    }

}
